package com.bookstore.back.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.bookstore.back.common.Result;
import com.bookstore.back.entity.Bestseller;
import com.bookstore.back.entity.Book;
import com.bookstore.back.entity.BookCategory;
import com.bookstore.back.entity.BookReview;
import com.bookstore.back.service.BestsellerService;
import com.bookstore.back.service.BookService;
import com.bookstore.back.service.CategoryService;
import com.bookstore.back.service.ReviewService;
import com.bookstore.back.vo.ReviewVO;
import com.bookstore.back.util.UserContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.HashMap;

/**
 * 图书控制器（面向前端用户）
 * 
 * @author 程序猿_Ti
 * @since 2025-07-22
 */
@Slf4j
@RestController
@RequestMapping("/books")
public class BookController {

    @Autowired
    private BookService bookService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private ReviewService reviewService;

    @Autowired
    private BestsellerService bestsellerService;

    @Autowired
    private UserContextUtil userContextUtil;

    /**
     * 获取推荐图书列表
     */
    @GetMapping("/recommended")
    public Result<List<Book>> getRecommendedBooks(@RequestParam(defaultValue = "10") Integer limit) {
        try {
            List<Book> books = bookService.getRecommendedBooks(limit);
            return Result.success(books);
        } catch (Exception e) {
            log.error("获取推荐图书失败：{}", e.getMessage());
            return Result.error("获取推荐图书失败");
        }
    }

    /**
     * 获取新书上架列表
     */
    @GetMapping("/new")
    public Result<List<Book>> getNewBooks(@RequestParam(defaultValue = "10") Integer limit) {
        try {
            List<Book> books = bookService.getNewBooks(limit);
            return Result.success(books);
        } catch (Exception e) {
            log.error("获取新书列表失败：{}", e.getMessage());
            return Result.error("获取新书列表失败");
        }
    }

    /**
     * 获取个性化推荐图书列表
     */
    @GetMapping("/personalized")
    public Result<List<Book>> getPersonalizedBooks(@RequestParam(defaultValue = "10") Integer limit) {
        try {
            // 获取当前用户ID（如果已登录）
            Long userId = null;
            try {
                userId = userContextUtil.getCurrentUserId();
            } catch (Exception e) {
                // 用户未登录，userId保持为null
                log.debug("用户未登录，返回通用推荐");
            }
            
            List<Book> books = bookService.getPersonalizedBooks(userId, limit);
            return Result.success(books);
        } catch (Exception e) {
            log.error("获取个性化推荐失败：{}", e.getMessage());
            return Result.error("获取个性化推荐失败");
        }
    }

    /**
     * 获取图书详情
     */
    @GetMapping("/{bookId}")
    public Result<Book> getBookDetail(@PathVariable Integer bookId) {
        try {
            Book book = bookService.getBookWithTags(bookId);
            if (book == null) {
                return Result.error("图书不存在");
            }
            return Result.success(book);
        } catch (Exception e) {
            log.error("获取图书详情失败：{}", e.getMessage());
            return Result.error("获取图书详情失败");
        }
    }

    /**
     * 获取热门图书列表
     */
    @GetMapping("/popular")
    public Result<List<Book>> getPopularBooks(@RequestParam(defaultValue = "10") Integer limit) {
        try {
            List<Book> books = bookService.getPopularBooks(limit);
            return Result.success(books);
        } catch (Exception e) {
            log.error("获取热门图书失败：{}", e.getMessage());
            return Result.error("获取热门图书失败");
        }
    }

    /**
     * 获取图书分类列表
     */
    @GetMapping("/categories")
    public Result<List<BookCategory>> getCategories() {
        try {
            List<BookCategory> categories = categoryService.getCategoryTree();
            return Result.success(categories);
        } catch (Exception e) {
            log.error("获取图书分类失败：{}", e.getMessage());
            return Result.error("获取图书分类失败");
        }
    }

    /**
     * 按分类获取图书列表
     */
    @GetMapping("/category/{categoryId}")
    public Result<IPage<Book>> getBooksByCategory(@PathVariable Integer categoryId, @RequestParam Map<String, Object> params) {
        try {
            // 添加分类ID到查询参数
            params.put("categoryId", categoryId.toString());
            IPage<Book> bookPage = bookService.getBookList(params);
            return Result.success(bookPage);
        } catch (Exception e) {
            log.error("按分类获取图书失败：{}", e.getMessage());
            return Result.error("按分类获取图书失败");
        }
    }

    /**
     * 搜索图书
     */
    @GetMapping("/search")
    public Result<IPage<Book>> searchBooks(@RequestParam Map<String, Object> params) {
        try {
            IPage<Book> bookPage = bookService.getBookList(params);
            return Result.success(bookPage);
        } catch (Exception e) {
            log.error("搜索图书失败：{}", e.getMessage());
            return Result.error("搜索图书失败");
        }
    }

    // ==================== 评论相关接口 ====================

    /**
     * 获取图书评论列表
     */
    @GetMapping("/{bookId}/reviews")
    public Result<IPage<ReviewVO>> getBookReviews(@PathVariable Integer bookId, @RequestParam Map<String, Object> params) {
        try {
            // 添加图书ID到查询参数
            params.put("bookId", bookId.toString());
            IPage<ReviewVO> reviewPage = reviewService.getReviewList(params);
            return Result.success(reviewPage);
        } catch (Exception e) {
            log.error("获取图书评论失败：{}", e.getMessage());
            return Result.error("获取图书评论失败");
        }
    }

    /**
     * 创建图书评论
     */
    @PostMapping("/{bookId}/reviews")
    public Result<String> createBookReview(@PathVariable Integer bookId, @RequestBody Map<String, Object> reviewData) {
        try {
            // 获取当前登录用户ID
            Long currentUserId = userContextUtil.getCurrentUserId();
            if (currentUserId == null) {
                return Result.error("请先登录");
            }

            // 验证当前用户是否为普通用户
            if (!userContextUtil.isCurrentUserRegular()) {
                return Result.error("权限不足，只有普通用户可以评论");
            }

            // 创建评论对象
            BookReview review = new BookReview();
            review.setBookId(bookId);
            review.setUserId(currentUserId.intValue());
            review.setContent((String) reviewData.get("content"));
            review.setRating((Integer) reviewData.get("rating"));
            review.setStatus(1); // 默认显示状态

            boolean success = reviewService.save(review);
            return success ? Result.success("评论成功") : Result.error("评论失败");
        } catch (Exception e) {
            log.error("创建图书评论失败：{}", e.getMessage());
            return Result.error("评论失败：" + e.getMessage());
        }
    }

    /**
     * 点赞/取消点赞评论
     */
    @PostMapping("/reviews/{reviewId}/like")
    public Result<String> toggleReviewLike(@PathVariable Integer reviewId) {
        Long currentUserId = userContextUtil.getCurrentUserId();
        if (currentUserId == null) {
            return Result.error("请先登录");
        }

        if (!userContextUtil.isCurrentUserRegular()) {
            return Result.error("权限不足");
        }

        boolean success = reviewService.toggleReviewLike(reviewId, currentUserId.intValue());
        return success ? Result.success("操作成功") : Result.error("操作失败");
    }

    /**
     * 获取畅销榜单列表（前端用户页面）
     */
    @GetMapping("/bestsellers")
    public Result<IPage<Bestseller>> getBestsellerList(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "20") Integer size,
            @RequestParam(required = false) Integer categoryId,
            @RequestParam(defaultValue = "monthly") String period) {
        try {
            Map<String, Object> params = new HashMap<>();
            params.put("current", current);
            params.put("size", size);
            // 处理categoryId：null或0都表示综合榜（使用-1标识）
            params.put("categoryId", (categoryId == null || categoryId == 0) ? "-1" : categoryId.toString());
            params.put("period", period);

            IPage<Bestseller> bestsellerPage = bestsellerService.getBestsellerList(params);
            return Result.success(bestsellerPage);
        } catch (Exception e) {
            log.error("获取畅销榜单失败：{}", e.getMessage());
            return Result.error("获取畅销榜单失败");
        }
    }
}
